// 管理app config
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter_deer/database/beans/get_config_guns_entity.dart';
import 'package:flutter_deer/res/constant.dart';

class UserConfigManager {

  // 内存缓存
  static List<GetConfigGunsEntity> _guns = [];

  // 存储 guns
  static void setOilGuns(List<GetConfigGunsEntity> oils) {
    // 处理gun的自定义字段
     for (var oil in oils) {
       oil.shelfList?.forEach((shelf) {
         shelf.goodsShortName = oil.goodsShortName;
         shelf.goodsSkuName = oil.goodsSkuName;
         shelf.goodsSkuPrice = oil.goodsSkuPrice;
         shelf.categoryId = oil.categoryId;
         shelf.unitName = oil.unitName;
       });
     }
     _guns.clear();
     _guns.addAll(oils);
     SpUtil.putObjectList(Constant.guns, oils);
  }

  // 获取 guns
  static List<GetConfigGunsEntity> getOilGuns() {
    if (_guns.isEmpty) {
      final rawList = SpUtil.getObjList<GetConfigGunsEntity>(
        Constant.guns,
        (map) => GetConfigGunsEntity.fromJson(map as Map<String, dynamic>),
      );

      if (rawList != null && rawList.isNotEmpty) {
        try {
          _guns = rawList
              .whereType<Map<String, dynamic>>()
              .map((item) => GetConfigGunsEntity.fromJson(item))
              .toList();
        } catch (e) {
          // 可根据项目日志系统记录异常
          print('解析枪械配置数据失败: $e');
          _guns = [];
        }
      } else {
        _guns = [];
      }
    }
    return List<GetConfigGunsEntity>.unmodifiable(_guns);
  }

  // 根据 gun 编号获取 gun 信息
  static ShelfBean? getGunByNzl(int nzl) {
    final List<GetConfigGunsEntity> oils = getOilGuns();
    for (var oil in oils) {
      if (oil.shelfList != null) {
        for (var shelf in oil.shelfList!) {
          if (shelf.shelfNo == nzl) {
            return shelf; // ✅ 正确返回
          }
        }
      }
    }
    return null; // 找不到时返回 null
  }

  // 根据油品获取枪号List
  static List<int> getNzlListByOilId(String oilId) {
      final List<int> nzlList = [];
      final List<GetConfigGunsEntity> oils = getOilGuns();
      for (var oil in oils) {
        if (oil.shelfList != null) {
          for (var shelf in oil.shelfList!) {
            if (shelf.goodsSkuId == oilId) {
              nzlList.add(shelf.shelfNo!); // ✅ 正确返回
            }
          }
        }
      }
      return nzlList; // 找不到时返回 null
  }
}